package com.cote.douhahou.pretloan.launcher;

import android.Manifest;
import android.annotation.SuppressLint;
import android.os.Bundle;
import android.text.Html;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageButton;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.cote.douhahou.pretloan.beans.PermissAkomapalendionInfo;
import com.cote.douhahou.pretloan.network.HttpHelper;
import com.cote.douhahou.pretloan.utils.AkomapaLendConfigs;
import com.cote.douhahou.pretloan.utils.AkomapaLendUtil;
import com.cote.douhahou.pretloan.utils.KindTipAkomapalendDialog;
import com.cote.douhahou.pretloan.R;

import java.util.ArrayList;
import java.util.List;

import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;


public class PermissionRequestActivity extends AppCompatActivity implements EasyPermissions.PermissionCallbacks, EasyPermissions.RationaleCallbacks {

    private Permission_akomapalendPicker_akomapalendView permissionPickerView;

    private TextView permissi_akomapalendonTi_akomapalendtleTv;
    private TextView permissio_akomapalendnTex_akomapalendtTv;
    private ImageButton permiss_akomapalendionReadIb;
    private View permissionRead_akomapalendView, permiss_akomapalendionAgreeView, permissionB_akomapalendtnView;
    private View den_akomapalendyBtn, agreeB_akomapalendtn;

    private ArrayList<PermissAkomapalendionInfo> permissio_akomapalendnInfos;

    private int selectPermission = 0;

    private float posX =0, curPosX =0;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_apply_permission);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);

        permissionPickerView = findViewById(R.id.apa_view_permission_picker);
        permissi_akomapalendonTi_akomapalendtleTv = findViewById(R.id.apa_tv_permission_title);
        permissio_akomapalendnTex_akomapalendtTv = findViewById(R.id.apa_tv_permission_text);
        permiss_akomapalendionReadIb = findViewById(R.id.apa_ib_permission_read);
        permissionRead_akomapalendView = findViewById(R.id.apa_view_permission_read);
        permiss_akomapalendionAgreeView = findViewById(R.id.apa_view_permission_agree);
        permissionB_akomapalendtnView = findViewById(R.id.apa_view_permission_btn);
        den_akomapalendyBtn = findViewById(R.id.apa_btn_deny);
        agreeB_akomapalendtn = findViewById(R.id.apa_btn_agree);

        in_akomapalendit();
    }

    @SuppressLint("ClickableViewAccessibility")
    private void in_akomapalendit(){

        permissio_akomapalendnInfos = AkomapaLendConfigs.PermissionInfoList;

        if (permissio_akomapalendnInfos.isEmpty()) {
            finish();
            return;
        }

        for (PermissAkomapalendionInfo permissi_akomapalendonI_akomapalendnfo: permissio_akomapalendnInfos){

            switch (permissi_akomapalendonI_akomapalendnfo.getPe_akomapalendrmission()){
                case AkomapaLendConfigs.PermissionSms:
                    permissi_akomapalendonI_akomapalendnfo.set_akomapalendPermission_akomapalendAgreeRunnable(smsPerm_akomapalendissionAgreeRunnable);
                    permissi_akomapalendonI_akomapalendnfo.setPermission_akomapalendDenyRunnable(smsPermiss_akomapalendionDenyRunnable);
                    break;
                case AkomapaLendConfigs.PermissionPhone:
                    permissi_akomapalendonI_akomapalendnfo.set_akomapalendPermission_akomapalendAgreeRunnable(phonestateP_akomapalendermissionAgreeRu_akomapalendnnable);
                    permissi_akomapalendonI_akomapalendnfo.setPermission_akomapalendDenyRunnable(phonestateP_akomapalendermissionDenyRun_akomapalendnable);
                    break;
                default:
                    permissi_akomapalendonI_akomapalendnfo.set_akomapalendPermission_akomapalendAgreeRunnable(applistPer_akomapalendmissionAgre_akomapalendeRunnable);
                    permissi_akomapalendonI_akomapalendnfo.setPermission_akomapalendDenyRunnable(applis_akomapalendtPermissionDenyRu_akomapalendnnable);
            }

        }

        permissionPickerView.setPermissionSel_akomapalendectListener(select -> {
            selectPermission = select;
            PermissAkomapalendionInfo permissionInfo = getSelec_akomapalendtPermis_akomapalendsionInfo();
            if (permissionInfo == null) return;
            permissi_akomapalendonTi_akomapalendtleTv.setText(permissionInfo.getT_akomapalenditle());
            permissio_akomapalendnTex_akomapalendtTv.setText(Html.fromHtml(permissionInfo.get_akomapalendText(),0));
            den_akomapalendyBtn.setOnClickListener(v -> permissionInfo.permissio_akomapalendnDenyRun());
            agreeB_akomapalendtn.setOnClickListener(v -> permissionInfo.permissi_akomapalendonAgreeRun());
            permiss_akomapalendionReadIb.setBackgroundResource(permissionInfo.is_akomapalendRead() ? R.drawable.icon_check9 :R.drawable.icon_no_check_2);
            permiss_akomapalendionReadIb.setOnClickListener(v -> {
                permissionInfo.set_akomapalendRead(!permissionInfo.is_akomapalendRead());
                permiss_akomapalendionReadIb.setBackgroundResource(permissionInfo.is_akomapalendRead() ? R.drawable.icon_check9 :R.drawable.icon_no_check_2);
            });
            refreshPer_akomapalendmissionSt_akomapalendate(permissionInfo.isAlre_akomapalendadyAgree());
        });


        findViewById(R.id.apa_view_slide).setOnTouchListener((v, event) -> {
            switch (event.getAction()){
                case MotionEvent.ACTION_DOWN:
                    posX = event.getX();
                    break;
                case MotionEvent.ACTION_MOVE:
                    curPosX = event.getX();
                    break;
                case MotionEvent.ACTION_UP:
                    if (curPosX-posX>0 && (Math.abs(curPosX-posX) > AkomapaLendConfigs.SlidMinOffset)) {
                        //左滑
                        permissionPickerView.setSelectPermis_akomapalendsion(selectPermission-1);
                    } else if (curPosX-posX<0 && (Math.abs(curPosX-posX) > AkomapaLendConfigs.SlidMinOffset)) {
                        //右滑
                        permissionPickerView.setSelectPermis_akomapalendsion(selectPermission+1);
                    }
                    break;
            }

            return false;
        });

        permissionPickerView.setSelectPermis_akomapalendsion(0);

    }

    private PermissAkomapalendionInfo getSelec_akomapalendtPermis_akomapalendsionInfo(){
        if (selectPermission<0||selectPermission>= permissio_akomapalendnInfos.size()) return null;
        return permissio_akomapalendnInfos.get(selectPermission);
    }

    private final Runnable smsPerm_akomapalendissionAgreeRunnable = () -> {

        HttpHelper.inst().submitEvent("PERMISSION","SMS_AGREE_CLICK","");
        PermissAkomapalendionInfo permissionInfo = getSelec_akomapalendtPermis_akomapalendsionInfo();
        if (permissionInfo == null) return;

        if (permissionInfo.is_akomapalendRead())
            EasyPermissions.requestPermissions(PermissionRequestActivity.this, getString(R.string.request_permission_sms), AkomapaLendConfigs.PermissionCSms, Manifest.permission.READ_SMS);
        else {
            new KindTipAkomapalendDialog(PermissionRequestActivity.this,
                    getString(R.string.king_tip_permission_read_text),
                    getString(R.string.cancel),
                    getString(R.string.ok),
                    () -> HttpHelper.inst().submitEvent("PERMISSION","SMS_CHECKBOX_DIALOG_NO_CLICK",""),
                    () -> {
                        HttpHelper.inst().submitEvent("PERMISSION","SMS_CHECKBOX_DIALOG_YES_CLICK","");
                        permiss_akomapalendionReadIb.setBackgroundResource(R.drawable.icon_check9);
                        permissionInfo.set_akomapalendRead(true);
                        EasyPermissions.requestPermissions(PermissionRequestActivity.this, getString(R.string.request_permission_sms), AkomapaLendConfigs.PermissionCSms, Manifest.permission.READ_SMS);
                    }
            ).show();
        }

    };

    private final Runnable smsPermiss_akomapalendionDenyRunnable = () -> {
        HttpHelper.inst().submitEvent("PERMISSION","SMS_DENY_CLICK","");
        nextPe_akomapalendrmission();
    };

    private final Runnable applistPer_akomapalendmissionAgre_akomapalendeRunnable = () -> {
        HttpHelper.inst().submitEvent("PERMISSION","APPS_AGREE_CLICK","");
        PermissAkomapalendionInfo permissionInfo = getSelec_akomapalendtPermis_akomapalendsionInfo();
        if (permissionInfo == null) return;

        if (permissionInfo.is_akomapalendRead()) nextPe_akomapalendrmission();
        else {
            new KindTipAkomapalendDialog(PermissionRequestActivity.this,
                    getString(R.string.king_tip_permission_read_text),
                    getString(R.string.cancel),
                    getString(R.string.ok),
                    () -> HttpHelper.inst().submitEvent("PERMISSION","APPS_CHECKBOX_DIALOG_NO_CLICK",""),
                    () -> {
                        HttpHelper.inst().submitEvent("PERMISSION","APPS_CHECKBOX_DIALOG_YES_CLICK","");
                        permiss_akomapalendionReadIb.setBackgroundResource(R.drawable.icon_check9);
                        permissionInfo.set_akomapalendRead(true);
                        nextPe_akomapalendrmission();
                    }
            ).show();
        }
    };

    private final Runnable applis_akomapalendtPermissionDenyRu_akomapalendnnable = () -> {
        HttpHelper.inst().submitEvent("PERMISSION","APPS_DENY_CLICK","");
        nextPe_akomapalendrmission();
    };

    private final Runnable phonestateP_akomapalendermissionAgreeRu_akomapalendnnable = () -> {
        HttpHelper.inst().submitEvent("PERMISSION","PHONE_STATE_AGREE_CLICK","");
        PermissAkomapalendionInfo permissionInfo = getSelec_akomapalendtPermis_akomapalendsionInfo();
        if (permissionInfo == null) return;

        if (permissionInfo.is_akomapalendRead())
            EasyPermissions.requestPermissions(PermissionRequestActivity.this, getString(R.string.request_permission_phonestate), AkomapaLendConfigs.PermissionCPhone, Manifest.permission.READ_PHONE_STATE);
        else {
            new KindTipAkomapalendDialog(PermissionRequestActivity.this,
                    getString(R.string.king_tip_permission_read_text),
                    getString(R.string.cancel),
                    getString(R.string.ok),
                    () -> HttpHelper.inst().submitEvent("PERMISSION","PHONE_STATE_CHECKBOX_DIALOG_NO_CLICK",""),
                    () -> {
                        HttpHelper.inst().submitEvent("PERMISSION","PHONE_STATE_CHECKBOX_DIALOG_YES_CLICK","");
                        permiss_akomapalendionReadIb.setBackgroundResource(R.drawable.icon_check9);
                        permissionInfo.set_akomapalendRead(true);
                        EasyPermissions.requestPermissions(PermissionRequestActivity.this, getString(R.string.request_permission_phonestate), AkomapaLendConfigs.PermissionCPhone, Manifest.permission.READ_PHONE_STATE);
                    }
            ).show();
        }
    };

    private final Runnable phonestateP_akomapalendermissionDenyRun_akomapalendnable = () -> {
        HttpHelper.inst().submitEvent("PERMISSION","PHONE_STATE_DENY_CLICK","");
        o_akomapalendut();
    };

    private void refreshPer_akomapalendmissionSt_akomapalendate(boolean isAlready){
        if (isAlready){
            permissionRead_akomapalendView.setVisibility(View.GONE);
            permiss_akomapalendionAgreeView.setVisibility(View.VISIBLE);
            permissionB_akomapalendtnView.setVisibility(View.GONE);
        }else {
            permissionRead_akomapalendView.setVisibility(View.VISIBLE);
            permiss_akomapalendionAgreeView.setVisibility(View.GONE);
            permissionB_akomapalendtnView.setVisibility(View.VISIBLE);
        }
    }

    private void nextPe_akomapalendrmission(){
        int nextSelect = selectPermission+1;
        if (nextSelect<0||nextSelect>= permissio_akomapalendnInfos.size()){
            if (AkomapaLendUtil.phonestatePermissionHasAgree(this)) finishPermissio_akomapalendnProcess();
            else o_akomapalendut();
        }else permissionPickerView.setSelectPermis_akomapalendsion(nextSelect);
    }

    private void finishPermissio_akomapalendnProcess(){
        setResult(RESULT_OK);
        finish();
    }

    private void o_akomapalendut(){
        setResult(82);
        finish();
    }

    @Override
    public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {

        switch (requestCode){
            case AkomapaLendConfigs.PermissionCSms:

                HttpHelper.inst().submitEvent("PERMISSION","SMS_2_DENY_CLICK","");
                if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
                    new AppSettingsDialog.Builder(this).build().show();
                }else nextPe_akomapalendrmission();

                break;

            case AkomapaLendConfigs.PermissionCPhone:

                HttpHelper.inst().submitEvent("PERMISSION","PHONE_STATE_2_DENY_CLICK","");
                if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
                    new AppSettingsDialog.Builder(this).build().show();
                }else o_akomapalendut();

                break;
        }
    }

    @Override
    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {
        PermissAkomapalendionInfo permissionInfo = getSelec_akomapalendtPermis_akomapalendsionInfo();
        switch (requestCode){
            case AkomapaLendConfigs.PermissionCSms:
                HttpHelper.inst().submitEvent("PERMISSION","SMS_GRANTED_AGREE_CLICK","");
                if (permissionInfo!=null) permissionInfo.setAlre_akomapalendadyAgree(true);
                refreshPer_akomapalendmissionSt_akomapalendate(true);
                nextPe_akomapalendrmission();
                break;
            case AkomapaLendConfigs.PermissionCPhone:
                HttpHelper.inst().submitEvent("PERMISSION","PHONE_STATE_GRANTED_AGREE_CLICK","");
                if (permissionInfo!=null) permissionInfo.setAlre_akomapalendadyAgree(true);
                refreshPer_akomapalendmissionSt_akomapalendate(true);
                nextPe_akomapalendrmission();
                break;
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    public void onRationaleAccepted(int requestCode) {
        switch (requestCode){
            case AkomapaLendConfigs.PermissionCSms:
                HttpHelper.inst().submitEvent("PERMISSION","SMS_RATIONALE_AGREE_CLICK","");
                EasyPermissions.requestPermissions(this, this.getString(R.string.request_permission_sms), AkomapaLendConfigs.PermissionCSms, Manifest.permission.READ_SMS);
                break;

            case AkomapaLendConfigs.PermissionCPhone:
                HttpHelper.inst().submitEvent("PERMISSION","PHONE_STATE_RATIONALE_AGREE_CLICK","");
                EasyPermissions.requestPermissions(this, this.getString(R.string.request_permission_phonestate), AkomapaLendConfigs.PermissionCPhone, Manifest.permission.READ_PHONE_STATE);
                break;
        }
    }

    @Override
    public void onRationaleDenied(int requestCode) {
        switch (requestCode){
            case AkomapaLendConfigs.PermissionCSms:
                HttpHelper.inst().submitEvent("PERMISSION","SMS_RATIONALE_DENY_CLICK","");
                break;

            case AkomapaLendConfigs.PermissionCPhone:
                HttpHelper.inst().submitEvent("PERMISSION","PHONE_STATE_RATIONALE_DENY_CLICK","");
                break;
        }
    }


    @Override
    protected void onResume() {
        super.onResume();
        HttpHelper.inst().submitEvent("PERMISSION","START","");
    }

    @Override
    protected void onPause() {
        super.onPause();
        HttpHelper.inst().submitEvent("PERMISSION","END","");
    }


}
